﻿using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Text;

namespace LibraryGuard
{
	/// <summary>
	/// Service installer.
	/// </summary>
	[RunInstaller(true)]
	public sealed class Installer
		: System.Configuration.Install.Installer
	{
		public Installer()
		{
			ServiceProcessInstaller process = new ServiceProcessInstaller();
			process.Account = ServiceAccount.LocalSystem; //We need to have write access to filesystem.

			ServiceInstaller service = new ServiceInstaller();
			service.StartType = ServiceStartMode.Manual;
			service.ServiceName = LibraryGuardService.Name;
			service.DisplayName = "Library Guard";
			
			this.Installers.Add(process);
			this.Installers.Add(service);
		}

		public override void Install(System.Collections.IDictionary stateSaver)
		{
			var cfgFile = this.Context.Parameters["configfile"];
			if (string.IsNullOrWhiteSpace(cfgFile))
			{
				System.Console.WriteLine("Usage:");
				System.Console.WriteLine("\tInstallUtil /ConfigFile=\"\" LibraryGuard.exe");
				throw new InstallException("Missing parameter 'ConfigFile'.");
			}

			var path = new StringBuilder(this.Context.Parameters["assemblypath"]);
			if (path[0] != '"')
			{
				path.Insert(0, '"');
				path.Append('"');
			}
			path.Append(" /Service");

			path.Append(" /ConfigFile:\"");
			path.Append(cfgFile);
			path.Append('"');

			this.Context.Parameters["assemblypath"] = path.ToString();

			base.Install(stateSaver);
		}
	}
}
